# -*- coding: UTF-8 -*-
import os, sys

def script_path():
	import inspect, os
	caller_file = inspect.stack()[1][1]         # caller's filename
	return os.path.abspath(os.path.dirname(caller_file))# path
g__source_folder = ""
local = script_path() #os.path.dirname(__file__)
class PSInfo():
    def __init__(self, file_path, line):
        global g__source_folder
        self.source_folder = g__source_folder
        self.file_path = file_path
        self.line = line
        line = line.replace("     ", " ")
        line = line.replace("     ", " ")
        line = line.replace("    ", " ")
        line = line.replace("   ", " ")
        line = line.replace("  ", " ")
        line = line.replace(" ", " ")
        arr = line.split(' ')
        self.is_ok = False
        if len(arr) < 10:
            print("len is:" + str(len(arr)))
            return
        text = arr[9]
        if len(arr) > 10:
            for i in range(10, len(arr) - 10):
                text += " " + arr[i].strip()
        arr[9] = text
        self.is_ok = True
        self.user = arr[0]
        self.pid = arr[1]
        self.cpu = arr[2]
        self.mem = arr[3]
        self.vsz = arr[4]
        self.rss = arr[5]
        self.tty = arr[6]
        self.stat = arr[7]
        self.time = arr[8]
        self.command = arr[9]
    def get_time(self):
        path = self.file_path.replace(self.source_folder, "")
        if path.startswith("/"):
            path = path[1:]
        arr = path.split("/")
        if len(arr) != 3:
            return path
        arr[0] = arr[0].replace("_", "-")
        arr[2] =  arr[2].replace("_", ":")
        return arr[0] + " " + str(arr[1]) + ":" + arr[2].replace(".log", "")
    def to_string(self):
        return "time:{4},pid:{0}, cpu:{1}, mem:{2}, command:{3}".format(self.pid, self.cpu, self.mem, self.command, self.get_time())
ps_list = {}
def parser_ps_line(f, line):
    line = line.replace("\n", "")
    ps = PSInfo(f, line)
    if not ps.is_ok:
        print(line + " is parser failed")
        return
    if ps.pid not in ps_list.keys():
        ps_list[ps.pid] = []
    ps_list.get(ps.pid).append(ps)
    
def  parser_ps(f):
    if not f.endswith(".log"):
        return
    fin = open(f)
    for i in fin:
        if len(i) < 10:
            continue
        if (i.startswith("USER")): # 第一行跳过
            continue
        parser_ps_line(f, i)
    fin.close()
    
def is_sys_folder(f):
    return f == "." or f == ".."
    

def init_folder(parent, sub_folder):
    path =  os.path.join(parent, sub_folder)
    if not os.path.exists(path):
        os.makedirs(path)
    else:
        del_list = os.listdir(path)
        for f in del_list:
            file_path = os.path.join(path, f)
            if os.path.isfile(file_path):
                os.remove(file_path)
    return path
    
    
def get_all_ps_files(path):
    global g__source_folder
    if g__source_folder == "":
        g__source_folder = path
    ls = os.listdir(path)
    for f in ls:
        if is_sys_folder(f):
            continue
        f_path = os.path.join(path, f)
        if os.path.isdir(f_path):
            get_all_ps_files(f_path)
            continue
        parser_ps(f_path)
        
        
    csv_path = init_folder(path, "csv")
    for i in ps_list.keys():
        file_path =  os.path.join(csv_path, str(i) + ".csv")
        file = open(file_path, "w+")
        file.write('"time", "cpu", "mem","command"\n')
        for ps in ps_list.get(i):
            file.write('"{time}", "{cpu}", "{mem}","{command}"\n'.format(time=ps.get_time(), cpu=ps.cpu,mem=ps.mem,command=ps.command))
        file.close()
        
if __name__ == '__main__':
    print(sys.argv[1])
    get_all_ps_files(sys.argv[1])
    